package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.common.admin.WemediaConstants;
import com.heima.common.constants.message.PublishArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Value("${file.oss.web-site}")
    String webSite;

    @Autowired
    WmNewsService wmNewsService;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public void autoScanWmNews(Integer id) {
        //1. 根据id查询自媒体文章数据
        log.info("成功 接收到文章自动审核消息， 待审核文章id", id);
        WmNews wmNews = wmNewsService.getById(id);
        if (wmNews == null) {
            log.error("文章不存在 自动审核失败  文章id:{}", id);
            CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST, "文章不存在 自动审核失败");
        }

        //2.判断文章状态是否为1（防止重复消费）
        Short status = wmNews.getStatus();
        if (!WemediaConstants.WM_NEWS_SUMMIT_STATUS.equals(status)) {
            log.error("文章状态不是待审核 自动审核失败 ");
            CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST, "文章状态不是待审核 自动审核失败");
        }
        //3.开始审核

        //3.0 抽取出 文章的所有文本内容和图片内容
        Map contentAndImages = parseContentAndImages(wmNews);
        //3.1 DFA自管理的敏感词审核
        boolean sensitive = handleSensitive((String) contentAndImages.get("content"), wmNews);
        if (!sensitive) {
            log.info("文章审核未通过，文章内容中有敏感词", id);
            return;
        }
        // 审核失败 状态改为2，说明失败原因
        //通过 下一步

        //3.2阿里云内容 文本审核
        boolean textScan = handleText((String) contentAndImages.get("content"), wmNews);
        if (!textScan) {
            log.info("文章阿里云文本审核未通过，文章内容中有敏感词", id);
            return;
        }
        //失败 状态改为2
        //待人工审核，状态3
        // 通过 下一步
        //3.3阿里云内容 图片审核
        List<String> images = (List<String>) contentAndImages.get("images");
        if (!CollectionUtils.isEmpty(images)) {
            boolean imageScan = handleImages(images, wmNews);
            if (!imageScan) {
                log.info("文章阿里云图片审核未通过，图片内容中有敏感", id);
                return;
            }
        }

        //失败 状态改为2
        //待人工审核，状态3
        // 4通过 改为8

        updateWmNews(wmNews, WmNews.Status.SUCCESS.getCode(), "审核通过");
        //5.根据文章的具体发布时间 发送延时消息
        // 5.1 计算延时时间
        long publishTime = wmNews.getPublishTime().getTime();
        long nowTime = new Date().getTime();
        long remainTime = publishTime - nowTime;
        //5.2 发送消息 并设置延迟时间
        rabbitTemplate.convertAndSend(
                PublishArticleConstants.DELAY_DIRECT_EXCHANGE,
                PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY,
                wmNews.getId(),
                new MessagePostProcessor() {
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {
                        //设置x-delay延迟时间
                        message.getMessageProperties().setHeader("x-delay", remainTime <= 0 ? 0 : remainTime);
                        return message;
                    }
                }
        );
        log.info("成功发送延时发布文章消息 文章id:{},延迟时间：{}" + wmNews.getId(), remainTime);
    }

    /*
     * 阿里云图片审核
     * */
    private boolean handleImages(List<String> images, WmNews wmNews) {
        boolean flag = false;
        try {
            ScanResult scanResult = greenScan.imageUrlScan(images);
            String suggestion = scanResult.getSuggestion();
            switch (suggestion) {
                case "block":
                    updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "图片内容有违规信息" + scanResult.getLabel());
                    break;
                case "review":
                    updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "图片有不确定信息 转为人工审核");
                    break;
                case "pass":
                    flag = true;
                    break;
                default:
                    updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "图片有不确定信息 转为人工审核");
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("阿里云 图片审核异常 改为人工审核");
            updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "阿里云 图片审核异常 改为人工审核");
        }
        return flag;
    }

    @Autowired
    GreenScan greenScan;

    private boolean handleText(String content, WmNews wmNews) {
        boolean flag = false;
        //1. 使用阿里云对文本审核
        try {
            ScanResult scanResult = greenScan.greenTextScan(content);
            String suggestion = scanResult.getSuggestion();
            switch (suggestion) {
                case "block":
                    updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "文章内容有违规信息" + scanResult.getLabel());
                    break;
                case "review":
                    updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "有不确定信息 转为人工审核");
                    break;
                case "pass":
                    flag = true;
                    break;
                default:
                    updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "有不确定信息 转为人工审核");
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            //如果报异常 状态改成3
            log.error("阿里云 文本审核异常 改为人工审核");
            updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "阿里云 文本审核异常 改为人工审核");
        }
        //2判断suggestion  block  review pass

        //3根据suggestion的值修改
        return flag;
    }

    //敏感词审核方法
    @Autowired
    AdminFeign adminFeign;

    private boolean handleSensitive(String content, WmNews wmNews) {
        //1.使用fegin远程查询敏感词列表
        ResponseResult<List<String>> sensitivesResult = adminFeign.sensitives();
        if (!sensitivesResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "查询敏感词调用失败");
        }
        List<String> sensitives = sensitivesResult.getData();

        //2.基于DFA算法 封装数据模型
        SensitiveWordUtil.initMap(sensitives);
        //3.基于DFA算法 检测
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if (!CollectionUtils.isEmpty(map)) {
            //状态改为2
            updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "文章中包含敏感词" + map);
            return false;
        }
        return true;
    }

    private void updateWmNews(WmNews wmNews, Short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsService.updateById(wmNews);
    }

    /*抽取文章内容和图片路径集合
     * */
    private Map parseContentAndImages(WmNews wmNews) {
        List<Map> contentMapList = JSON.parseArray(wmNews.getContent(), Map.class);
        //1. 抽取文章文本内容
        String content = contentMapList.stream()
                .filter(m -> "text".equals(m.get("type")))
                .map(m -> String.valueOf(m.get("value")))
                .collect(Collectors.joining("_hmtt_"));
        //文章标题和文本
        content += "_hmtt_" + wmNews.getTitle();

        //2.抽取文章图片
        List<String> images = contentMapList.stream()
                .filter(m -> "image".equals(m.get("type")))
                .map(m -> String.valueOf(m.get("value")))
                .collect(Collectors.toList());
        //标题图片  文本图片
        String coverStr = wmNews.getImages();
        if (StringUtils.isNotBlank(coverStr)) {
            //数据库里的都是相对路径，需要加上webSite
            //1. 按照逗号切割 得到数据
            //2.基于数据 获取流对象
            //3.使用map映射，将每个路径添加访问前缀
            List<String> coverImages = Arrays.stream(coverStr.split(","))
                    .map(url -> webSite + url)
                    .collect(Collectors.toList());
            images.addAll(coverImages);
        }
        //去除重复的图片
        images = images.stream()
                .distinct()
                .collect(Collectors.toList());

        Map result = new HashMap();
        result.put("content", content);
        result.put("images", images);
        return result;

    }
}
